import json
import urllib.request

api_url = "http://openapi.tuling123.com/openapi/api/v2"


def tuling(text_input):
    req = {
        "perception":
            {
                "inputText":
                    {
                        "text": text_input
                    },

                "selfInfo":
                    {
                        "location":
                            {
                                "city": "",
                                "province": "",
                                "street": ""
                            }
                    }
            },

        "userInfo":
            {
                "apiKey": "d9ec6d9233d0f65d2374656aea530e95",
                "userId": "OnlyUseAlphabet"
            }
    }
    # print(req)
    # 将字典格式的req编码为utf8
    req = json.dumps(req).encode('utf8')
    # print(req)

    http_post = urllib.request.Request(api_url, data=req, headers={'content-type': 'application/json'})
    response = urllib.request.urlopen(http_post)
    response_str = response.read().decode('utf8')
    print(response_str)

    response_dic = json.loads(response_str)

    intent_code = response_dic['intent']['code']
    results_text = response_dic['results'][0]['values']['text']
    print('Turing的回答：')
    print('code：' + str(intent_code))
    print('text：' + results_text)
    return format_result(response_dic['results'])


def format_result(results):
    re_type = results[0]['resultType']
    re_vals = results[0]['values']

    if len(results) == 1:
        return re_vals[re_type]
    else:
        re_type = results[1]['resultType']
        re_vals = results[1]['values']
        list_vals = re_vals[re_type]
        item_name = list_vals[0].get('name')
        item_url = list_vals[0].get('detailurl')
        print(item_name)
        print(item_url)
        msg = item_name + '\r\n' + item_url
        cq_msg = '[CQ:share,url={detailurl},title={name},content='',image={icon}]'.format(**list_vals[0])

        return cq_msg


if __name__ == '__main__':
    text_input = input('我：')
    print('图灵：' + tuling(text_input))
